package com.green.springsecuritydemo1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 使用的是6.3.1 配置类有一些变化
 * 1、该类不再需要继承其他的security定义类
 * 2、需要使用 Configuration注解才会被spring容器加载
 * 3、废弃很多方法，比如and()方法，建议使用lambda表示实现
 */

//测试：通过内存加载用户信息
//@Configuration
//标记为一个security类，启用Springsecurity的自定义配置
//@EnableWebSecurity
public class SecurityConfig {

    //自定义用户名和密码
    //UserDetailsService:根据用户名加载用户，找到的话返回用户信息，返回UserDetails类型
    //UserDetails存储了用户的信息
    @Bean
    public UserDetailsService userDetailsService() {
        //定义用户信息
        UserDetails admin = User.withUsername("xiaozhang")
                .password("$2a$10$fNrR4Ou.P.krlK9CRHtkNub3bWw2RUD7qKwDMzNrM75fH5b74sG5u")
                .roles("admin", "user")
                .build();

        UserDetails vipUser = User.withUsername("user")
                .password("$2a$10$fNrR4Ou.P.krlK9CRHtkNub3bWw2RUD7qKwDMzNrM75fH5b74sG5u")
                .roles("", "user")
                .build();
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        userDetailsManager.createUser(admin);
        userDetailsManager.createUser(vipUser);
        return userDetailsManager;
    }
    @Bean
    public BCryptPasswordEncoder passwordEncoder () {
        //构建密码编码器
        return new BCryptPasswordEncoder();
    }
}
